<template>
  <zz-Dialog
    v-model="open"
    @ok="ok"
    :size="'large'"
    @close="close"
    align-center
    :title="title"
  >
    <div class="select-db-tables">
      <!-- 顶部布局 -->
      <el-header>
        <zz-Search
          :searchOptions="searchOptions"
          @getSearchData="getSearchData"
        ></zz-Search>
      </el-header>
      <!-- 内容区 -->
      <el-main style="height: 400px">
        <zz-Table
          ref="dbTableRef"
          :data="dbTable"
          :hasPage="true"
          :page="dbTablePage"
          :loading="loading"
          @pageChange="pageChange"
        >
          <vxe-column
            type="checkbox"
            title=""
            fixed="left"
            width="40"
          ></vxe-column>
          <vxe-column
            type="seq"
            title="序号"
            fixed="left"
            width="50"
          ></vxe-column>
          <vxe-column
            field="tableName"
            title="表名称"
            :min-width="150"
          ></vxe-column>
          <vxe-column
            field="tableComment"
            title="表描述"
            :min-width="200"
          ></vxe-column>
          <vxe-column
            field="createDate"
            title="创建时间"
            :min-width="150"
            :formatter="
              ({ cellValue }) => $TOOL.format.formatDateTime(cellValue)
            "
          >
          </vxe-column>
          <vxe-column
            field="updateDate"
            title="更新时间"
            :min-width="150"
            :formatter="
              ({ cellValue }) => $TOOL.format.formatDateTime(cellValue)
            "
          >
          </vxe-column>
        </zz-Table>
      </el-main>
    </div>
  </zz-Dialog>
</template>

<script setup>
import { computed, watch, ref, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  system: {
    type: String,
    default: "",
    required: true,
  },
});
const emit = defineEmits(["update:modelValue", "query"]);
const open = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

watch(
  open,
  (newValue, oldValue) => {
    if (newValue) {
      query("search");
    }
  },
  { immediate: true }
);

// 查询model
const searchModel = ref({
  tableName: "",
  tableComment: "",
});

const searchOptions = computed(() => {
  return {
    // 接收字段
    model: searchModel,
    // 配置表单
    column: [
      {
        label: "表名称",
        type: "inputText",
        field: "tableName",
      },
      {
        label: "表描述",
        type: "inputText",
        field: "tableComment",
      },
    ],
  };
});

const getSearchData = (val) => {
  searchModel.value = val;
  query("search");
};

const loading = ref(false);
const dbTable = ref([]);
const dbTableRef = ref(null);
const dbTablePage = ref({ pageNum: 1, pageSize: 15, total: 0 });
const query = async (mode) => {
  loading.value = true;
  if (mode === "search") {
    searchModel.value.queryParam = {
      pageNum: 1,
      pageSize: 15,
      total: 0,
    };
  }
  let param = {
    ...searchModel.value,
  };

  try {
    let res = await proxy.$API.codeManagement.codeGen.selectDbTables.post(
      props.system,
      param
    );
    if (res.code === "01") {
      dbTable.value = res.bizList;
      dbTablePage.value.total = res.total;
      dbTablePage.value.pageSize = res.pageSize;
    } else {
      ElMessage.error("查询失败");
    }
  } catch (error) {
    console.error("查询失败:", error);
    ElMessage.error("查询失败");
  } finally {
    loading.value = false;
  }
};

const title = ref("");
// 确定
const ok = async () => {
  let arr = dbTableRef.value.getCheckboxRecords();
  if (arr.length == 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  let param = arr.map((e) => e.tableName);
  // TODO: 替换为实际的API调用
  try {
    let res = await proxy.$API.codeManagement.codeGen.importTable.post(
      props.system,
      param,
      localStorage.getItem("language") || "zh-CN"
    );
    if (res.code == "01") {
      ElMessage.success("导入成功");
      emit("query");
      open.value = false;
    } else {
      ElMessage.error("导入失败");
    }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败");
  }
};

// 翻页
const pageChange = (page) => {
  searchModel.value.queryParam.pageNum = page.currentPage;
  searchModel.value.queryParam.pageSize = page.pageSize;
  query();
};

// 取消
const close = () => {};

defineExpose({ title });
</script>

<style lang="less" scoped></style>
